<template>
<div>
  <p>{{label}}</p>
  <slot></slot>
  <p v-if="error" class="error">{{error}}</p>
</div>
</template>

<script>
import Schema from 'async-validator'
import emitter from '../utils/emitter'
export default {
  inject: ['form'],
  mixins: [emitter],
  componentName: 'KFormItem',
  props: {
    label: {
      type: String,
      defalt: ''
    },
    prop: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      error: ''
    }
  },
  mounted() {
    if (this.prop) {
      this.dispatch('KFrom', 'kform.addField', [this])
    }
    this.$on('kform.change', () => {
      this.validate()
    })
  },
  methods: {
    validate() {
      // 当前规则
      const rules = this.form.rules[this.prop]
      // 值
      const value = this.form.model[this.prop]
      // 校验描述对象
      const desc = {
        [this.prop]: rules
      }
      // 创建实例
      const schema = new Schema(desc)
      return schema.validate({
        [this.prop]: value
      }, error => {
        if (error) {
          this.error = error[0].message
        } else {
          this.error = ''
        }
      })
    }
  }
}
</script>

<style>
.error {
  color: red;
}
</style>
